import {
  setMemberId, setCustomerId, setPhone, setVisitorId, setEnterpriseId, setVeekrayStatus, setEnterprisePhone,
  setShowBuyCard, setStoreCardFlag, setMemberNature, setAppInfo, setCartBadge, setMemberCommanderEnable,
  setFastGoods, setNavList, setCurrentPickup, setCustomerCommanderStatus, setMemberCommanderStatus,
  setIsCommunityGroupExtraction, setIsHomeDelivery, setIsStoreExtraction, setMemberStoreState,
  setImToken, setImSellerToList, setImBuyerToList, setDeliveryType, setPayMethod, setCbFlag,
  setImUnreadSeller, setImUnreadBuyer, setInMessage } from '@/utils/auth'
import { checkLogin } from '@/api/login'
import { setNickName } from '../utils/auth'
import { appColor } from '@/api/appColor'
import { getAppInfo } from '@/api/common'
// 融云第三方消息
// import { imWatch } from '@/api/im'
// imWatch()

export default {
  data() {
    return {
      isComponents: false,
      fileSpace: process.env.FILE_SPACE, // 文件服务器地址
      socketUrl: process.env.SOCKET_URL, // socket服务器地址
      h5Url: process.env.H5_URL, // h5链接地址
      submitted: false, // 是否已经提交，防止重复提交
      isResetMethodInitData: false
    }
  },
  onLoad(options) {
    // APP页面第一次载入时，重新获取访客购买信息
    if (!this.globalData.isAppLoad) {
      // 记录状态，防止每个页面执行
      this.globalData.isAppLoad = true
    }
  },
  onShow() {
    this.initMixinEls()
  },
  computed: {
    // 访客是否是名片主
    checkOwner() {
      return this.getMemberId === this.getCustomerId && this.getMemberId
    },
    // 名片主id（注意：不要在data中直接赋值，可能取不到，可以在mounted赋值）
    getMemberId() {
      let memberId = this.$store.state.memberId
      if (!memberId) {
        const storageMemberId = this.$pt.getStorageSync('memberId')
        setMemberId(storageMemberId)
        memberId = this.$store.state.memberId
      }
      return memberId
    },
    // 名片主昵称（注意：不要在data中直接赋值，可能取不到，可以在mounted赋值）
    getNickName() {
      let nickName = this.$store.state.nickName
      if (!nickName) {
        const storageNickName = this.$pt.getStorageSync('nickName')
        setNickName(storageNickName)
        nickName = this.$store.state.nickName
      }
      return nickName
    },
    // 访客id（注意：不要在data中直接赋值，可能取不到，可以在mounted赋值）
    getCustomerId() {
      let customerId = this.$store.state.customerId
      if (!customerId) {
        const storageCustomerId = this.$pt.getStorageSync('customerId')
        setCustomerId(storageCustomerId)
        customerId = this.$store.state.customerId
      }
      return customerId
    },
    // 访客id（注意：不要在data中直接赋值，可能取不到，可以在mounted赋值）
    getPhone() {
      let phone = this.$store.state.phone
      if (!phone) {
        const storagePhone = this.$pt.getStorageSync('phone')
        setPhone(storagePhone)
        phone = this.$store.state.phone
      }
      return phone
    },
    // 支付类型
    getPayMethod() {
      let payMethod = this.$store.state.payMethod
      if (!payMethod) {
        const storagePayMethod = this.$pt.getStorageSync('payMethod')
        setPayMethod(storagePayMethod)
        payMethod = this.$store.state.payMethod
      }
      return payMethod
    },
    // 跨境增值功能
    getCbFlag() {
      let cbFlag = this.$store.state.cbFlag
      if (!cbFlag) {
        const storageCbFlag = this.$pt.getStorageSync('cbFlag')
        setCbFlag(storageCbFlag)
        cbFlag = this.$store.state.cbFlag
      }
      return cbFlag
    },
    // 游客id（注意：不要在data中直接赋值，可能取不到，可以在mounted赋值）
    getVisitorId() {
      let visitorId = this.$store.state.visitorId
      if (!visitorId) {
        const storageVisitorId = this.$pt.getStorageSync('visitorId')
        setVisitorId(storageVisitorId)
        visitorId = this.$store.state.visitorId
      }
      return visitorId
    },
    // 企业id（注意：不要在data中直接赋值，可能取不到，可以在mounted赋值）
    getEnterpriseId() {
      let enterpriseId = this.$store.state.enterpriseId
      if (!enterpriseId) {
        const storageEnterpriseId = this.$pt.getStorageSync('enterpriseId')
        setEnterpriseId(storageEnterpriseId)
        enterpriseId = this.$store.state.enterpriseId
      }
      return enterpriseId
    },
    // 访客名片状态 0：未购买 1：已购买 2：已过期
    getVeekrayStatus() {
      let veekrayStatus = this.$store.state.veekrayStatus
      if (!veekrayStatus) {
        const storageVeekrayStatus = this.$pt.getStorageSync('veekrayStatus')
        setVeekrayStatus(storageVeekrayStatus)
        veekrayStatus = this.$store.state.veekrayStatus
      }
      return veekrayStatus
    },
    // 是否是门店版名片 0.不是 1.是
    getStoreCardFlag() {
      let storeCardFlag = this.$store.state.storeCardFlag
      if (!storeCardFlag) {
        const storageStoreCardFlag = this.$pt.getStorageSync('storeCardFlag')
        setStoreCardFlag(storageStoreCardFlag)
        storeCardFlag = this.$store.state.storeCardFlag
      }
      return storeCardFlag
    },
    // 店长微客性质 0.公共微客 1.外部微客 2.内部微客
    getMemberNature() {
      let memberNature = this.$store.state.memberNature
      if (!memberNature) {
        const storageMemberNature = this.$pt.getStorageSync('memberNature')
        setMemberNature(storageMemberNature)
        memberNature = this.$store.state.memberNature
      }
      return memberNature
    },
    // 是否显示购买名片页面
    getShowBuyCard() {
      let showBuyCard = this.$store.state.showBuyCard
      if (!showBuyCard) {
        const storageShowBuyCard = this.$pt.getStorageSync('showBuyCard')
        setShowBuyCard(storageShowBuyCard)
        showBuyCard = this.$store.state.showBuyCard
      }
      return showBuyCard
    },
    // 购物车角标
    getCartBadge() {
      let cartBadge = this.$store.state.cartBadge
      if (!cartBadge) {
        const storageCartBadge = this.$pt.getStorageSync('cartBadge')
        setCartBadge(storageCartBadge)
        cartBadge = this.$store.state.cartBadge
      }
      return cartBadge
    },
    // 快速购买商品列表
    getFastGoods() {
      let fastGoods = this.$store.state.fastGoods
      if (!fastGoods) {
        const storageFastGoods = this.$pt.getStorageSync('fastGoods')
        setFastGoods(storageFastGoods)
        fastGoods = this.$store.state.fastGoods
      }
      return fastGoods
    },
    // 底部导航列表
    getNavList() {
      let navList = this.$store.state.navList
      if (!navList) {
        const storageNavList = this.$pt.getStorageSync('navList')
        setNavList(storageNavList)
        navList = this.$store.state.navList
      }
      return navList
    },
    // 是否社区团购提货点
    getIsCommunityGroupExtraction() {
      let isCommunityGroupExtraction = this.$store.state.isCommunityGroupExtraction
      if (!isCommunityGroupExtraction) {
        const storageIsCommunityGroupExtraction = this.$pt.getStorageSync('isCommunityGroupExtraction')
        setIsCommunityGroupExtraction(storageIsCommunityGroupExtraction)
        isCommunityGroupExtraction = this.$store.state.isCommunityGroupExtraction
      }
      return isCommunityGroupExtraction
    },
    // 是否到家配送点
    getIsHomeDelivery() {
      let isHomeDelivery = this.$store.state.isHomeDelivery
      if (!isHomeDelivery) {
        const storageIsHomeDelivery = this.$pt.getStorageSync('isHomeDelivery')
        setIsHomeDelivery(storageIsHomeDelivery)
        isHomeDelivery = this.$store.state.isHomeDelivery
      }
      return isHomeDelivery
    },
    // 是否门店自提点
    getIsStoreExtraction() {
      let isStoreExtraction = this.$store.state.isStoreExtraction
      if (!isStoreExtraction) {
        const storageIsStoreExtraction = this.$pt.getStorageSync('isStoreExtraction')
        setIsStoreExtraction(storageIsStoreExtraction)
        isStoreExtraction = this.$store.state.isStoreExtraction
      }
      return isStoreExtraction
    },
    // 当前自提点
    getCurrentPickup() {
      let currentPickup = this.$store.state.currentPickup
      if (!currentPickup) {
        const storageCurrentPickup = this.$pt.getStorageSync('currentPickup')
        setCurrentPickup(storageCurrentPickup)
        currentPickup = this.$store.state.currentPickup
      }
      return currentPickup
    },
    // 顾客团长状态 0：未成为团长 1：已是团长
    getCustomerCommanderStatus() {
      let customerCommanderStatus = this.$store.state.customerCommanderStatus
      if (!customerCommanderStatus) {
        const storageCustomerCommanderStatus = this.$pt.getStorageSync('customerCommanderStatus')
        setCustomerCommanderStatus(storageCustomerCommanderStatus)
        customerCommanderStatus = this.$store.state.customerCommanderStatus
      }
      return customerCommanderStatus
    },
    // 店主团长状态 0：未成为团长 1：已是团长
    getMemberCommanderStatus() {
      let memberCommanderStatus = this.$store.state.memberCommanderStatus
      if (!memberCommanderStatus) {
        const storageMemberCommanderStatus = this.$pt.getStorageSync('memberCommanderStatus')
        setMemberCommanderStatus(storageMemberCommanderStatus)
        memberCommanderStatus = this.$store.state.memberCommanderStatus
      }
      return memberCommanderStatus
    },
    // 店主团长开启状态 0：禁用 1：启用
    getMemberCommanderEnable() {
      let memberCommanderEnable = this.$store.state.memberCommanderEnable
      if (!memberCommanderEnable) {
        const storageMemberCommanderEnable = this.$pt.getStorageSync('memberCommanderEnable')
        setMemberCommanderEnable(storageMemberCommanderEnable)
        memberCommanderEnable = this.$store.state.memberCommanderEnable
      }
      return memberCommanderEnable
    },
    // 门店开启状态 0：禁用 1：启用
    getMemberStoreState() {
      let memberStoreState = this.$store.state.memberStoreState
      if (!memberStoreState) {
        const storageMemberStoreState = this.$pt.getStorageSync('memberStoreState')
        setMemberStoreState(storageMemberStoreState)
        memberStoreState = this.$store.state.memberStoreState
      }
      return memberStoreState
    },
    // 平台客服电话
    getEnterprisePhone() {
      let enterprisePhone = this.$store.state.enterprisePhone
      if (!enterprisePhone) {
        const storageEnterprisePhone = this.$pt.getStorageSync('enterprisePhone')
        setEnterprisePhone(storageEnterprisePhone)
        enterprisePhone = this.$store.state.enterprisePhone
      }
      return enterprisePhone
    },
    // 配送类型
    getDeliveryType() {
      let deliveryType = this.$store.state.deliveryType
      if (!deliveryType) {
        const storageDeliveryType = this.$pt.getStorageSync('deliveryType')
        setDeliveryType(storageDeliveryType)
        deliveryType = this.$store.state.currentPickup
      }
      return deliveryType
    },
    // getImToken
    getImToken() {
      let imToken = this.$store.state.imToken
      if (!imToken) {
        const storageImToken = this.$pt.getStorageSync('imToken')
        setImToken(storageImToken)
        imToken = this.$store.state.imToken
      }
      return imToken
    },
    // im卖家消息列表
    getImSellerToList() {
      let imSellerToList = this.$store.state.imSellerToList
      if (!imSellerToList) {
        const storageImSellerToList = this.$pt.getStorageSync('imSellerToList')
        setImSellerToList(storageImSellerToList)
        imSellerToList = this.$store.state.imSellerToList
      }
      return imSellerToList
    },
    // im买家消息列表
    getImBuyerToList() {
      let imBuyerToList = this.$store.state.imBuyerToList
      if (!imBuyerToList) {
        const storageImBuyerToList = this.$pt.getStorageSync('imBuyerToList')
        setImBuyerToList(storageImBuyerToList)
        imBuyerToList = this.$store.state.imBuyerToList
      }
      return imBuyerToList
    },
    // im卖家会话总未读数
    getImUnreadSeller() {
      let imUnreadSeller = this.$store.state.imUnreadSeller
      if (!imUnreadSeller) {
        const storageImUnreadSeller = this.$pt.getStorageSync('imUnreadSeller')
        setImUnreadSeller(storageImUnreadSeller)
        imUnreadSeller = this.$store.state.imUnreadSeller
      }
      return imUnreadSeller
    },
    // im买家会话总未读数
    getImUnreadBuyer() {
      let imUnreadBuyer = this.$store.state.imUnreadBuyer
      if (!imUnreadBuyer) {
        const storageImUnreadBuyer = this.$pt.getStorageSync('imUnreadBuyer')
        setImUnreadBuyer(storageImUnreadBuyer)
        imUnreadBuyer = this.$store.state.imUnreadBuyer
      }
      return imUnreadBuyer
    },
    // 是否有新消息
    getInMessage() {
      let inMessage = this.$store.state.inMessage
      if (!inMessage) {
        const storageInMessage = this.$pt.getStorageSync('inMessage')
        setInMessage(storageInMessage)
        inMessage = this.$store.state.showBuyCard
      }
      return inMessage
    }
  },
  methods: {
    initMixinEls() {
      // 如果是组件，不执行以下逻辑
      if (!this.isComponents) {
        // 页面载入，清除本页数据状态
        if (!this.isResetMethodInitData) {
          this.setMethodInitData(this.getCurrentPage().page.route)
          this.isResetMethodInitData = true
        }
        // 不是名片主页也可以访问的页面
        const whiteList = [
          'pages/home/main',
          'pages/home/buy/main',
          'pages/home/buy/service/main',
          'pages/home/buy/legal/main',
          'pages/home/card-qr-code/main',
          'pages/home/live-share/main',
          'pages/shop/main',
          'pages/shop/detail/main',
          'pages/shop/buy/main',
          'pages/shop/cart/main',
          'pages/shop/result/main',
          'pages/personal/main',
          'pages/personal/customer/main',
          'pages/live-player-plugin',
          'pages/personal/message/list/main'
        ]
        // 校验路由白名单
        if (whiteList.indexOf(this.getCurrentPage().page.route) === -1) {
          // 判断购买状态是否有效
          if (this.getVeekrayStatus === '') {
            if (process.env.NODE_ENV === 'development') {
              // 开发环境不校验，因为调试不方便
              return true
            }
            // this.$utils.showToast({ title: '没有权限' })
            this.$pt.reLaunch({url: '/pages/home/main'})
            return false
          }
        }
        let appStorageInfo = this.$pt.getStorageSync('appInfo')
        if (appStorageInfo) {
          this.memberIdSetEls(appStorageInfo.defaultMemberId)
        } else {
          this.getAppEls('again')
        }
      }
    },
    memberIdSetEls(defaultMemberId) {
      // 选择地理位置，会重启运行整个项目
      if (this.$pt.getStorageSync('chooseLocation')) return
      // 如果扫描或者通过分享链接或者名片切换，url会带上memberId
      let memberId = this.$root.$mp.appOptions.query.memberId
      if (memberId) {
        this.$utils.removeMyId('myId')
      }
      let myId = this.$pt.getStorageSync('myId')
      if (myId) {
        this.$utils.setMyId(myId)
        setMemberId(myId)
      }
      if (memberId && !myId && !this.$root.$mp.appOptions.query.address && !this.$root.$mp.appOptions.query.addressId) {
        this.$utils.removeMyId('myId')
        setMemberId(memberId)
        this.$utils.setMyId(memberId)
      }
      if (!memberId && !myId) {
        setMemberId(this.getCustomerId)
        this.$utils.setMyId(this.getCustomerId)
      }
      // 新用户查看名片首页处理
      if (this.getShowBuyCard === false) {
        setMemberId(defaultMemberId)
        this.$utils.setMyId(defaultMemberId)
      }
      // 判断访客是否登录微信
      if (!this.getMemberId || this.getVeekrayStatus === '') {
        checkLogin(this.getMemberId, this.getCustomerId)
      }
      if (this.getVeekrayStatus === 0 && this.getCustomerId === this.getMemberId) {
        if (!this.$pt.getStorageSync('scanCode')) {
          setMemberId(defaultMemberId)
          this.$utils.setMyId(defaultMemberId)
          this.$pt.reLaunch({ url: '/pages/home/main' })
        }
      }
    },
    getAppEls(type) {
      getAppInfo().then((response) => {
        if (response.isError) return
        let appInfo = response.data
        let versionNo = String(process.env.VERSION).split('')
        appInfo.appVersion = versionNo.join('.')
        let styleObj = {}
        if (appInfo.style) {
          styleObj = appColor(appInfo.style.styleType)
          styleObj.styleName = appInfo.style.styleName
          styleObj.styleType = appInfo.style.styleType
          appInfo.style = styleObj
        }
        setAppInfo(appInfo)
        if (type === 'again') {
          this.initMixinEls()
        }
      }).catch(() => {
      })
    },
    // 获取当前路由
    getCurrentPage() {
      return this.$root.$mp
    },
    // 设置方法数据的加载状态
    setMethodInitData(page, method) {
      if (method) {
        this.$store.commit('setMethodInitData', {page: page, method: method, value: false})
      } else {
        // 清除本页方法数据的加载状态
        this.$store.commit('setMethodInitData', {page: page})
      }
    },
    // 获取方法数据的加载状态
    getMethodInitData(page, method) {
      let isInit = false
      if (this.$store.state.isMethodInitData[page]) {
        isInit = this.$store.state.isMethodInitData[page][method]
      }
      if (!isInit) {
        // 设置数据已经读取过了
        this.$store.commit('setMethodInitData', {page: page, method: method, value: true})
      }
      return isInit
    }
  }
}
